const bcrypt = require('bcryptjs');
const { getUserInfo } = require('../service/user.service')
const { userFormateError, userAlreadyExist, userRegisterError, userDoesNotExist, userLoginError, invalidPassswordError } = require('../constant/err.type.js')

// 用户密码为空
const userValidator = async (ctx, next) => {
   // 合法性
   const { user_name, password } = ctx.request.body;
   if (!user_name || !password) {
      console.error("用户名或密码为空", ctx.request.body);
      ctx.app.emit('error', userFormateError, ctx);
      return;
   }
   await next();
}

// 用户名已存在
const verifyUser = async (ctx, next) => {
   const { user_name } = ctx.request.body;
   // 合理性
   try {
      const res = await getUserInfo({ user_name });
      if (res) {
         console.error("用户已存在", { user_name });
         ctx.app.emit('error', userAlreadyExist, ctx);
         return
      }
   } catch (err) {
      console.error("获取用户信息错误", err);
      ctx.app.emit('error', userRegisterError, ctx);
      return
   }
   await next();
}

// 密码加密处理
const cryptPassword = async (ctx, next) => {
   const { password } = ctx.request.body;
   const salt = bcrypt.genSaltSync(10);
   try {
      // 需要密码的字符串
      const hash1 = bcrypt.hashSync(password, salt);
   } catch (err) {
      console.error("密码加密错误", err);
      ctx.app.emit('error', userRegisterError, ctx);
      return
   }
   const hash = bcrypt.hashSync(password, salt);
   ctx.request.body.password = hash;
   // console.log("密码加密处理", ctx.request.body.password);
   await next();
}

// 验证用户登录
const verifyLogin = async (ctx, next) => {
   const { user_name, password } = ctx.request.body;
   try {
      const res = await getUserInfo({ user_name });
      if (!res) {
         console.error("用户不存在", { user_name });
         ctx.app.emit('error', userDoesNotExist, ctx);
         return
      }
      const isMatch = bcrypt.compareSync(password, res.password);
      if (!isMatch) {
         console.error("密码错误", { user_name });
         ctx.app.emit('error', invalidPassswordError, ctx);
         return
      }
   } catch (err) {
      console.error("获取用户信息错误", err);
      ctx.app.emit('error', userLoginError, ctx);
      return
   }
   await next();
}

module.exports = {
   userValidator,
   verifyUser,
   cryptPassword,
   verifyLogin
}